#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;
    vector<vector<int>> graph(n + 1, vector<int>(n + 1, INT_MAX));
    for (int i = 0; i < m; i++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u][v] = w;
        graph[v][u] = w;
    }
    vector<vector<int>> dp = graph;
    for (int k = 1; k <= n; k++)
    {
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                if(dp[i][k]!=INT_MAX && dp[k][j]!=INT_MAX)
                {
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
                }
            }
        }
    }
    int q, start, end;
    cin >> q;
    while (q--)
    {
        cin >> start >> end;
        if (dp[start][end] == INT_MAX)
        {
            cout << -1 << endl;
        }
        else
        {
            cout << dp[start][end] << endl;
        }
    }
    return 0;
}